package com.coded2.infra.comum;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import com.coded2.infra.interceptor.transactional.Transaction;
import com.coded2.infra.util.Util;

public  class   ComumService<MODEL extends ComumDTO> implements Serializable{
	
	private static final long serialVersionUID = -7042616908103277495L;
	
	@Inject
	protected EntityManager em;
	

	@Transaction
	public List<String> save(MODEL obj){
		
		List<String>errors = preSave(obj);
		if(errors==null || errors.isEmpty()){
			
			em.persist(obj);
		}
		return errors;
	}

	protected List<String> preSave(MODEL obj) {
		List<String>errors = preDelete();
		
		return errors;
	}
	
	public List<MODEL> search(MODEL obj)throws Exception{
		throw new NotImplementedException();
		
	}

	@SuppressWarnings("unchecked")
	public MODEL searchByID(MODEL model)throws Exception{
		throw new NotImplementedException();
	}
	
	@Transaction
	public List<String> update(MODEL obj){
		
		List<String>errors = preUpdate(obj);
		if(errors==null || errors.isEmpty()){
			
			em.merge(obj);
		}
		return errors;
	}

	protected List<String> preUpdate(MODEL obj){
		List<String>errors = new ArrayList<String>();
		return errors;
	}
	
	
	
	@SuppressWarnings("unchecked")
	@Transaction
	public List<String> remove(MODEL model) {
		List<String>erros = preDelete();
		if(Util.isEmpty(erros)){
			model = (MODEL) em.getReference(model.getClass(), model.getId());
			em.remove(model);
		}
		return erros;
	}

	private List<String> preDelete() {
		List<String>errors = new ArrayList<String>();
		return  errors;
	}
}